//同级的effect.js文件
// 两个状态
const STATUS_STOP = 'stop'
const STATUS_RUNNING = 'running'
//“基”类-这里就直接当“下雨”类了
class Particle {
	constructor(ctx, width, height, opts) {
		this._timer = null
		this._options = opts || {}
		// canvas 上下文
		this.ctx = ctx
		this.status = STATUS_STOP
		this.w = width
		this.h = height

		this._init()
	}
	_init() {
		// _init
		let h = this.h
		let w = this.w
		// 数量，根据不同雨大小，数量可调
		let amount = this._options.amount || 100
		// 速度参数，调节下落速度
		let speedFactor = this._options.speedFactor || 0.03
		let speed = speedFactor * h
		let ps = this.particles = []
		for (let i = 0; i < amount; i++) {
			let p = {
				x: Math.random() * w,
				y: Math.random() * h,
				l: 2 * Math.random(),
				xs: -1,
				ys: 10 * Math.random() + speed,
				color: 'rgba(46, 46, 46,0.3)'
			}
			ps.push(p)
		}
	}
	_draw() {
		// _draw
		let ps = this.particles
		let ctx = this.ctx
		// 清空画布
		ctx.clearRect(0, 0, this.w, this.h)
		// 遍历绘制雨滴
		for (let i = 0; i < ps.length; i++) {
			let s = ps[i]
			ctx.beginPath()
			ctx.moveTo(s.x, s.y)
			// 画线绘制雨点效果
			ctx.lineTo(s.x + s.l * s.xs, s.y + s.l * s.ys)
			ctx.setStrokeStyle(s.color)
			ctx.stroke()
		}
		ctx.draw()
		return this._update()
	}
	_update() {
		// _update
		let {
			w,
			h
		} = this // 获取画布大小
		for (let ps = this.particles, i = 0; i < ps.length; i++) {
			// 开始下一个周期的位置计算
			let s = ps[i]
			s.x += s.xs
			s.y += s.ys
			// 超出范围，重新回收，重复利用
			if (s.x > w || s.y > h) {
				s.x = Math.random() * w
				s.y = -10
			}
		}
	}
	run() {
		if (this.status !== STATUS_RUNNING) {
			// 更改状态
			this.status = STATUS_RUNNING
			// 绘制循环
			this._timer = setInterval(() => {
				this._draw()
			}, 30)

		}
		return this
	}
	stop() {
		// 清理定时器，状态修改
		this.status = STATUS_STOP
		clearInterval(this._timer)
		return this
	}
	clear() {
		this.stop()
		this.ctx.clearRect(0, 0, this.w, this.h)
		this.ctx.draw()
		return this
	}
}
exports.Particle = Particle
